package com.base.game.terrain;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

public class Heightmap {

	private final static String RENDER_IMAGE_LOCATION = "res/heightmap/heightmap.png";

	private int width, height; 
	private int octave;
	float[][] baseHeightValues;
	
	public Heightmap(int w, int h, int octave, boolean doRenderToFile) {
		this.width = w;
		this.height =  h ; 
		this.octave = octave;
		this.generateHeightmap();
		if(doRenderToFile)
			this.renderToFile();
	}

	public float[][] cutSection(int loX, int loZ, int hiX, int hiZ){
		int deltaX = hiX - loX ;
		int deltaZ = hiZ - loZ ; 
		float[][] res = new float[deltaX][deltaZ]; 
		for(int x=0; x<deltaX; x++)
			for(int z=0; z<deltaZ; z++){
				int _x = x + loX ; 
				int _z = z + loZ ; 
				if(_x>=0 && _x<this.baseHeightValues.length && _z>=0 && _z<this.baseHeightValues[x].length)
					res[x][z] = this.baseHeightValues[_x][_z]; 
			}
		return res ; 
	}
	
	private void generateHeightmap() {
		this.baseHeightValues = PerlinNoise.GeneratePerlinNoise(this.width,
				this.height, octave);
	}

	private void renderToFile() {
		BufferedImage img = new BufferedImage(this.width, this.height,
				BufferedImage.TYPE_INT_RGB);
		try {
			for (int x = 0; x < this.width; x++) {
				for (int y = 0; y < this.height; y++) {
					int h = (int) (this.baseHeightValues[x][y] * 255);
					Color c = new Color(h, h, h);
					img.setRGB(x, y, c.getRGB());
				}
			}
			ImageIO.write(img, "png", new File(RENDER_IMAGE_LOCATION));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static Heightmap intersect(Heightmap h1, int w, int h, int octave){
		Heightmap res = new Heightmap(w, h, octave, false) ; 
		if(h1 != null && h1.width == res.width && h1.height == res.height){
			for (int x = 0; x < h1.width; x++) {
				for (int y = 0; y < h1.height; y++) {
					float val = (h1.baseHeightValues[x][y] + res.baseHeightValues[x][y]) / 2.0f ;
					res.baseHeightValues[x][y] = val ; 
				}
			}
		}
		return res ; 
	}

	public static Heightmap intersect(int w, int h, int octave1, int octave2){
		Heightmap res = new Heightmap(w, h, octave1, false); 
		return intersect(res, w, h, octave2); 
	}
	
	
}
